import axios from 'axios';
import type { User } from '~/types/User';

export const useAuth = () => {
    const user = useState<User | null>('user', () => null);
    const token = useState<string | null>('token', () => null);

    const login = async (loginRequest: Pick<User, 'username' | 'password'>) => {
        try {
            const response = await axios.post('/auth/login', loginRequest);
            if (response.data.success) {
                token.value = response.data.data.token;
                // You might want to fetch user details here or store them from login response
                // For now, we'll just store a mock user
                user.value = {
                    username: loginRequest.username,
                    nickname: 'User',
                    email: '',
                    phone: ''
                };
                axios.defaults.headers.common['Authorization'] = `Bearer ${token.value}`;
                return navigateTo('/');
            }
            // Handle login failure
            console.error(response.data.message);
            return response.data;
        } catch (error) {
            console.error('Login failed', error);
        }
    };

    const register = async (registerRequest: User) => {
        try {
            const response = await axios.post('/auth/register', registerRequest);
            if (response.data.success) {
                return navigateTo('/login');
            }
            // Handle registration failure
            console.error(response.data.message);
            return response.data;
        } catch (error) {
            console.error('Registration failed', error);
        }
    };

    const logout = async () => {
        try {
            if(token.value) {
                await axios.post('/auth/logout', {}, {
                    headers: {
                        Authorization: `Bearer ${token.value}`
                    }
                });
            }
        } catch (error) {
            console.error('Logout failed', error);
        } finally {
            user.value = null;
            token.value = null;
            delete axios.defaults.headers.common['Authorization'];
            await navigateTo('/login');
        }
    };

    const checkAuth = async () => {
        if (!token.value) {
            return;
        }
        try {
            axios.defaults.headers.common['Authorization'] = `Bearer ${token.value}`;
            const response = await axios.get('/auth/validate');
            if(!response.data.success) {
                await logout();
            }
        } catch (error) {
            await logout();
        }
    }

    return {
        user,
        token,
        login,
        register,
        logout,
        checkAuth
    };
}; 